import requests
from datetime import datetime
import json
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
#定义时间及输入base_usr(网址)和params（参数）以及header（头文件）
def fetch_data(start_time, end_time):
    base_url = "https://sqfb.slt.zj.gov.cn/rest/newList/getNewTotalRainList"
    params = {
        "areaFlag": "1",
        "sss": "金华市",
        "ssx": "兰溪市",
        "st": start_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "et": end_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "ly": "",
        "max": "",
        "min": "0",
        "bool": "false",
        "bxdj": "1,2,3,4,5,",
        "zm": "",
        "type": "0",
        "lx": "QX,ME,SX,DS"
    }

    headers = {
        "User-Agent":"Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14"
    }
    #读取网站数据
    response = requests.get(base_url, params=params,headers=headers,verify=False)
    response.encoding = "utf-8"
    
    #读取雨量数据
    data = json.loads(response.text)

    #把字典中所有列表合并
    merged_list = [value for value_list in data.values() for value in value_list]
    
    
    #传递属性到DataFrame里        
    data1 = []
    for line in merged_list:
      data1.append(line)
    
    df = pd.DataFrame(data1)
    
    #将X,Y坐标单独提取赋值
    x_values = df["jd"]
    y_values = df["wd"]
   
    #建立GEODataFrame，zip()为内置函数目的为打包为元组
    geometry = [Point(xy) for xy in zip(x_values, y_values)]
    crs = {'init': 'epsg:4326'}  # 使用WGS84坐标系
    gdf = gpd.GeoDataFrame(df, crs=crs, geometry=geometry)
        
    #输出到excel表格里
    excle_file = r"G:\2024工作\应急雨量汇总\reslust{}.xlsx".format(start_time.strftime("%Y-%m-%d"))

    df.to_excel(excle_file,sheet_name="雨量",startcol=0,index=False)
    #输出到GDB文件
    gdb_path = r"G:\2024工作\应急雨量汇总\reslust{}.gdb".format(start_time.strftime("%Y-%m-%d"))

    gdf.to_file(gdb_path,driver='OpenFileGDB', encoding='utf-8')
    
    print("输出完毕")

#开始和结束时间   
start_time = datetime(2024, 6, 9, 00, 00, 00)
end_time = datetime(2024, 7, 4, 00, 00, 00)

fetch_data(start_time,end_time)

